package cc.orange.mainView;

import android.os.Handler;
import android.animation.Animator;
import android.animation.ObjectAnimator;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.Fragment;

import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.google.gson.Gson;
import com.xcheng.retrofit.Call;
import com.xcheng.retrofit.DefaultCallback;
import com.xcheng.retrofit.HttpError;
import com.xcheng.retrofit.RetrofitFactory;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import cc.orange.R;
import cc.orange.base.BaseFragment;
import cc.orange.databinding.FragmentMsgListBinding;
import cc.orange.entity.BaseEntity;
import cc.orange.entity.HightEntity;
import cc.orange.entity.IsLoginsEntity;
import cc.orange.entity.LoginsEntity;
import cc.orange.entity.MsgLoginUI3Entity;
import cc.orange.entity.SuerInfosEntity;
import cc.orange.entity.UpdataUserPostEntity;
import cc.orange.http.ApiService;
import cc.orange.utils.CheckNotifyPermissionUtils;
import cc.orange.utils.NotificaUtils;
import cc.orange.utils.RequestPermissions;
import cc.orange.utils.ZXToastUtil;
import demo.smart.access.xutlis.util.ZXSharedPrefUtil;
import okhttp3.MediaType;
import okhttp3.RequestBody;

public class MsgListFragment extends BaseFragment implements View.OnClickListener{

    private FragmentMsgListBinding binding;
    private SuerInfosEntity entity;
    private Handler handler = new Handler(){
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            if(msg.what == 1){
                initHeadVisb();
            }
        }
    };
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        binding = DataBindingUtil.inflate(inflater,R.layout.fragment_msg_list,container,false);
        EventBus.getDefault().register(this);
        initViews();
        return binding.getRoot();
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void getHight(IsLoginsEntity entity){
        if(entity.isLogins()){
            initHeadVisb();
            binding.msglistRel4.setVisibility(View.VISIBLE);
            binding.msglistRel5.setVisibility(View.VISIBLE);
        }else{

        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN,sticky = true)
    public void getHight(SuerInfosEntity entity){
        if(entity.getCode() == 0){
                this.entity = entity;
                RequestOptions qe = new RequestOptions();
                qe.error(entity.getData().getSex() == 1 ? R.drawable.icon_login_img3:R.drawable.icon_login_img4);
                Glide.with(getActivity()).load(entity.getData().getHeadPhoto()).apply(qe).into(binding.msglistImg1);

                binding.msglistText7.setText(entity.getData().getName());

                if(entity.getData().getSpareStatus().equals("0")){
                    binding.msglistRel3.setVisibility(View.GONE);
                    binding.msglistRel31.setVisibility(View.VISIBLE);
                }else{
                    binding.msglistRel31.setVisibility(View.GONE);
                    binding.msglistRel3.setVisibility(View.VISIBLE);
                    ZXSharedPrefUtil ss = new ZXSharedPrefUtil();
                    ss.putInt("hand_1", 1);
                    ss.putInt("hand_2", 1);
                    initHeadVisb();
                }
                checkNotf();
        }else{

        }
    }


    private void initViews() {
        binding.msglistRel2.setOnClickListener(this);
        binding.msglistRel311.setOnClickListener(this);
        binding.msglistRel312.setOnClickListener(this);
        binding.msglistRel3s1.setOnClickListener(this);
        binding.msglistRel3s2.setOnClickListener(this);
        binding.msglistRel3s3.setOnClickListener(this);
        binding.msglistRel5.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                Intent intent = new Intent(getActivity(),InfoMsgActivity.class);
//                startActivity(intent);
            }
        });

        initHeadVisb();
        ZXSharedPrefUtil ss = new ZXSharedPrefUtil();
        boolean isLogin = ss.getBool("isLogin_hr",false);
        if(isLogin) {
            binding.msglistRel4.setVisibility(View.VISIBLE);
            binding.msglistRel5.setVisibility(View.VISIBLE);
        }else{
            binding.msglistRel4.setVisibility(View.GONE);
            binding.msglistRel5.setVisibility(View.GONE);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void getHight(HightEntity entity) {//改变布局
        Log.v("---->3",""+entity.getHight());
        if(entity.getHight() > 0){
            RelativeLayout.LayoutParams pp = new RelativeLayout.
                    LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                    entity.getHight());
            binding.msglistTitle.setLayoutParams(pp);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void getHight(String str) {//青少年模式
        if(entity == null || entity.getData() == null)return;
        if(str.contains("Teenagers") || str.contains("true")){
            String s1 = entity.getData().getSpareStatus().equals("1") ? "0" : "1";//0无分身,1有分身
            if(s1.equals("0")){
                updateSpareStatus();
            }
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    private void checkNotf() {
        boolean b1 = CheckNotifyPermissionUtils.checkNotifyPermission(getActivity());
        if(entity == null || entity.getData() == null){
            binding.msglistRel2.setVisibility(View.GONE);
        }else {
            if (entity.getData().getNewsRemind().equals("0")) {//是否开启消息提醒(0关闭,1开启)
                binding.msglistRel2.setVisibility(View.VISIBLE);
            } else if (entity.getData().getNewsRemind().equals("1") && b1) {//是否开启消息提醒(0关闭,1开启)
                binding.msglistRel2.setVisibility(View.GONE);
            } else {
                binding.msglistRel2.setVisibility(View.VISIBLE);
            }
        }
    }


    private void updateSpareStatus(){
        if(null == entity || entity.getData() == null)return;
        String s1 = entity.getData().getSpareStatus().equals("1") ? "0" : "1";//0无分身,1有分身
        String s = "{\"spareStatus\":\""+s1+"\"}";//分身状态(0无分身,1有分身)
        RequestBody requestBody1 = RequestBody.create(MediaType.parse("application/json"), s.toString());

        RetrofitFactory.create(ApiService.class)
                .updateSpareStatus(getTokens(),requestBody1)
                .enqueue(new DefaultCallback<BaseEntity>() {
                    @Override
                    public void onStart(Call<BaseEntity> call) {
                        showLoading_base(getActivity());
                    }

                    @Override
                    public void onError(Call<BaseEntity> call, HttpError error) {
                        cancelLoading();
                        EventBus.getDefault().post(new MsgLoginUI3Entity(true));
                    }

                    @Override
                    public void onSuccess(Call<BaseEntity> call, BaseEntity baseEntity) {
                        cancelLoading();
                        if(baseEntity.getCode() == 0){
                            if(s1.equals("0")){
                                entity.getData().setSpareStatus(s1);
                                binding.msglistRel3.setVisibility(View.GONE);
                                binding.msglistRel31.setVisibility(View.VISIBLE);
                            }else{
                                entity.getData().setSpareStatus(s1);
                                binding.msglistRel31.setVisibility(View.GONE);
                                binding.msglistRel3.setVisibility(View.VISIBLE);
                            }
                            EventBus.getDefault().post(new String("home_refres"));
                        }else{
                            ZXToastUtil.showToast(baseEntity.getMsg());
                        }

                        ZXSharedPrefUtil ss = new ZXSharedPrefUtil();
                        ss.putInt("hand_2", 1);
                        initHeadVisb();
                    }
                });
    }

    @Override
    public void onClick(View v) {
        ZXSharedPrefUtil ss = new ZXSharedPrefUtil();
       boolean isLogin = ss.getBool("isLogin_hr",false);
        String token_hr = ss.getString("token_hr");
        if(!isLogin || TextUtils.isEmpty(token_hr)){
            ZXToastUtil.showToast("请先登录");
            startActivity(new Intent(getActivity(),LoginActivity.class));
            return;
        }
        switch (v.getId()){
            case R.id.msglist_rel2:
                RequestPermissions.getPermissions_notfi(getActivity(), new RequestPermissions.SuccessInterf() {
                    @RequiresApi(api = Build.VERSION_CODES.O)
                    @Override
                    public void onSuccess() {
                        if(entity != null && entity.getData() != null ){
                            entity.getData().getNewsRemind().equals("1");
                            updateNotify();
                        }else{
                            binding.msglistRel2.setVisibility(View.GONE);
                        }
                    }
                });
                break;
            case R.id.msglist_rel31_1://正常模式 1
                updateSpareStatus();
                break;
            case R.id.msglist_rel31_2://正常模式 2
                ss.putInt("hand_1", 1);
                Intent intent = new Intent(getActivity(),ShellLikeActivity.class);
                startActivity(intent);
                handler.sendEmptyMessageDelayed(1,1000);
                break;

            case R.id.msglist_rel3s_1://分身模式 1
                ss.putInt("hand_3", 1);
                Intent intent2 = new Intent(getActivity(),FateShakeActivity.class);
                startActivity(intent2);
                handler.sendEmptyMessageDelayed(1,1000);
                break;

            case R.id.msglist_rel3s_2://分身模式 2
                updateSpareStatus();
                break;

            case R.id.msglist_rel3s_3://分身模式 3
                Intent intent1 = new Intent(getActivity(),ShellLikeActivity.class);
                startActivity(intent1);
                break;
        }
    }

    private void updateNotify(){
        UpdataUserPostEntity entitys = new UpdataUserPostEntity();
        entitys.setNewsRemind("1");
        Gson gss = new Gson();
        String s = gss.toJson(entitys);
        RequestBody requestBody1 = RequestBody.create(MediaType.parse("application/json"), s.toString());

        RetrofitFactory.create(ApiService.class)
                .updateUser(getTokens(),requestBody1)
                .enqueue(new DefaultCallback<LoginsEntity>() {
                    @Override
                    public void onStart(Call<LoginsEntity> call) {
                        showLoading_base(getActivity());
                    }

                    @Override
                    public void onError(Call<LoginsEntity> call, HttpError error) {
                        cancelLoading();
                    }

                    @Override
                    public void onSuccess(Call<LoginsEntity> call, LoginsEntity baseEntity) {
                        cancelLoading();
                        if(baseEntity.getCode() == 0){
                            ZXToastUtil.showToast("已开启聊天消息提醒");
                            EventBus.getDefault().post(new String("getsus"));
                        }else{
                        }
                    }
                });
    }

    private void initHeadVisb() {
        ZXSharedPrefUtil ss = new ZXSharedPrefUtil();
        boolean isLogin = ss.getBool("isLogin_hr",false);
        if(!isLogin )return;

        int hand_1 = ss.getInt("hand_1", 0);
        if (hand_1 == 0  && binding.msglistRel31.getVisibility() == View.VISIBLE) {
            binding.homeHend1.setVisibility(View.VISIBLE);
            initHandAnim(binding.homeHend1);
            binding.homeHend2.setVisibility(View.GONE);
            binding.homeHend11.setVisibility(View.GONE);
            return;
        } else {
            binding.homeHend1.clearAnimation();
            binding.homeHend1.setVisibility(View.GONE);
        }

        int hand_2 = ss.getInt("hand_2", 0);
        if (hand_2 == 0  && binding.msglistRel31.getVisibility() == View.VISIBLE) {
            binding.homeHend11.setVisibility(View.VISIBLE);
            initHandAnim(binding.homeHend11);
            binding.homeHend2.setVisibility(View.GONE);
            binding.homeHend1.setVisibility(View.GONE);
            return;
        } else {
            binding.homeHend11.clearAnimation();
            binding.homeHend11.setVisibility(View.GONE);
        }

        int hand_3 = ss.getInt("hand_3", 0);
        if (hand_3 == 0 && binding.msglistRel3.getVisibility() == View.VISIBLE) {
            binding.homeHend2.setVisibility(View.VISIBLE);
            binding.homeHend1.setVisibility(View.GONE);
            binding.homeHend11.setVisibility(View.GONE);
            initHandAnim(binding.homeHend2);
            return;
        } else {
            binding.homeHend2.clearAnimation();
            binding.homeHend2.setVisibility(View.GONE);
        }

    }


        private void initHandAnim(View view){
        ObjectAnimator scaleX7 = ObjectAnimator.ofFloat(view, "translationY", 0f,20, 0f);
        ObjectAnimator scaleY7 = ObjectAnimator.ofFloat(view, "translationY", 0f,-20, 0f);
        scaleX7.setDuration(1500);
        scaleY7.setDuration(1500);
        scaleX7.start();
        scaleX7.addListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animation) {

            }

            @Override
            public void onAnimationEnd(Animator animation) {
                scaleY7.start();
            }

            @Override
            public void onAnimationCancel(Animator animation) {

            }

            @Override
            public void onAnimationRepeat(Animator animation) {

            }
        });

        scaleY7.addListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animation) {

            }

            @Override
            public void onAnimationEnd(Animator animation) {
                scaleX7.start();
            }

            @Override
            public void onAnimationCancel(Animator animation) {

            }

            @Override
            public void onAnimationRepeat(Animator animation) {

            }
        });
    }
}